// pages/setPhone/setPhone.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    code:'',
    isResend:false,
    second:60,
    isSend:false
  },
  phoneIpt(e){
    this.toggle('phone', e.detail.value)
  },
  codeIpt(e){
    this.toggle('code', e.detail.value)
    if (e.detail.value.length >=6){
      this.toggle('isSend',true)
    }else{
      this.toggle('isSend', false)
    }
  },
  toSetPhone(){
    var that = this
    if (that.data.isSend){
      app.req({
        url: 'orgmini/sys/updateTel',
        data:{
          "code": that.data.code ,
          "tel": that.data.phone
        },
        success: function (res) {
          if (200 == res.code) {
           wx.showToast({
             title: res.msg
           })
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2]; // 上一级页面
            prevPage.setData({
              phone: that.data.phone
            })
           wx.navigateBack({})
          }
        }
      });
    }
  },
  getCode(){
    var that = this
    var tel = /^1[3456789]\d{9}$/
    if (that.data.phone.length == 11 && tel.test(that.data.phone)){
      var url = "orgmini/sys/sendCode?telphone=" + that.data.phone + "&type=1"
      app.req({
        url: url,
        success: function (res) {
          if (200 == res.code) {
            that.toggle("isResend", true)
            var timer = setInterval(function () {
              that.toggle("second", --that.data.second)
              if (that.data.second < 0) {
                clearInterval(timer)
                that.toggle("isResend", false)
                that.toggle("second", 60)
              }
            }, 1000)
          }
        }
      });
    }else{
      wx.showToast({
        title: '请输入正确手机号码',
        icon:'none'
      })
    }
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    app.getUserInfo(function (userInfo) {
      that.toggle('uid',userInfo.id)
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})